package com.sijibao.amap;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


/**
 * 高德地图页面
 * @author JiangLiangJun
 *
 */
public class AMapActivity extends FragmentActivity implements  OnMarkerClickListener ,AMapLocationListener,LocationSource{
	
	private AMap aMap;
	private MapView mapView;
	
	
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	
	
	private MarkerOptions markerOption;
	
	public String   data;
	
	List<Address> addressList;

	private ImageView backView;
	private TextView titleText;
	
	private RouteSearch routeSearch;
	
	private DriveRouteResult driveRouteResult;// 驾车模式查询结果

	private String title="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.amap_sijibao_main);
		
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState); // 此方法必须重写
		
		titleText=(TextView)findViewById(R.id.title);
		title=getIntent().getStringExtra("title");
		if(title!=null&&!title.equals("")){
			titleText.setText(title);
		}
		
		
		backView=(ImageView)findViewById(R.id.back);
		backView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		
		init();
	}
	
	
	/**
	 * 初始化AMap对象
	 */
	private void init() {
//		markerText = (TextView) findViewById(R.id.mark_listenter_text);
//		radioOption = (RadioGroup) findViewById(R.id.custom_info_window_options);
//		Button clearMap = (Button) findViewById(R.id.clearMap);
//		clearMap.setOnClickListener(this);
//		Button resetMap = (Button) findViewById(R.id.resetMap);
//		resetMap.setOnClickListener(this);
		
		
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
		routeSearch = new RouteSearch(this);
		routeSearch.setRouteSearchListener(new OnRouteSearchListener() {
			
			@Override
			public void onWalkRouteSearched(WalkRouteResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
				// TODO Auto-generated method stub
				if (rCode == 0) {
					if (result != null && result.getPaths() != null
							&& result.getPaths().size() > 0) {
						driveRouteResult = result;
						DrivePath drivePath = driveRouteResult.getPaths().get(0);
						
						//aMap.clear();// 清理地图上的所有覆盖物
						DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
								AMapActivity.this, aMap, drivePath, driveRouteResult.getStartPos(),
								driveRouteResult.getTargetPos());
					
						drivingRouteOverlay.removeFromMap();
						drivingRouteOverlay.addToMap();
						drivingRouteOverlay.zoomToSpan();
					} else {
						//ToastUtil.show(RouteActivity.this, R.string.no_result);
					}
				} else if (rCode == 27) {
					//ToastUtil.show(RouteActivity.this, R.string.error_network);
				} else if (rCode == 32) {
					query();
					//Toast.makeText(AMapActivity.this, "无效的key", 2000).show();
					
				} else {
					//ToastUtil.show(RouteActivity.this, R.string.error_other);
				}
			}
			
			@Override
			public void onBusRouteSearched(BusRouteResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		
		
		
		
		
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		aMap.setInfoWindowAdapter(new InfoWindowAdapter() {
			
			@Override
			public View getInfoWindow(Marker marker) {
				// TODO Auto-generated method stub
				
				View infoWindow = getLayoutInflater().inflate(
						R.layout.custom_info_window, null);

				render(marker, infoWindow);
				return infoWindow;
				
			}
			
			@Override
			public View getInfoContents(Marker arg0) {
				// TODO Auto-generated method stub
				return null;
			}
		});
		
		
		aMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker marker) {
				// TODO Auto-generated method stub
				marker.hideInfoWindow();
			}
		});
		
		data=getIntent().getStringExtra("data");
		
		if(data!=null){
			
			
			addressList = new Gson().fromJson(data,  new TypeToken<List<Address>>() {  }.getType() );
			if(addressList!=null&&addressList.size()>0){
				
				drawMarkers(addressList);
				setLocation(addressList.get(0));
				if(addressList.size()==1){
					setLocation(addressList.get(0));
				}else{
					
					query();
					
					//setLine(addressList);
				}
//				startAddress=addressList.get(0).name;
//				endAddress=addressList.get(addressList.size()-1).name;
			}
			
		}else{
			Toast.makeText(this, "请传入正确的经纬度", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		// 自定义系统定位小蓝点
		MyLocationStyle myLocationStyle = new MyLocationStyle();
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory
				.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
		myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
		// myLocationStyle.radiusFillColor(color)//设置圆形的填充颜色
		// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
		myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
		aMap.setMyLocationStyle(myLocationStyle);
		aMap.setMyLocationRotateAngle(180);
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(false);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//		aMap.getUiSettings().setRotateGesturesEnabled(false);
	}
	
	
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是5000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			mAMapLocationManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 5000, 10, this);
		}
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}
	
	
	private void query(){
		
		RouteSearch.FromAndTo fromAndTo = new  RouteSearch.FromAndTo(
				new LatLonPoint(addressList.get(0).latitude, addressList.get(0).longitude)
				, new LatLonPoint(addressList.get(addressList.size()-1).latitude, addressList.get(addressList.size()-1).longitude)
				) ;
		
		List<LatLonPoint> mids = new ArrayList<LatLonPoint>();
		for(int i=1;i<addressList.size()-1;i++){
			LatLonPoint latLonPoint = new LatLonPoint(addressList.get(i).latitude, addressList.get(i).longitude);
			mids.add(latLonPoint);
		}
		DriveRouteQuery query = new DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault,
				mids, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，
		//第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
		routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
	}
	
	
	
	/**
	 * 自定义infowinfow窗口
	 */
	public void render(Marker marker, View view) {
//		if (radioOption.getCheckedRadioButtonId() == R.id.custom_info_contents) {
//			((ImageView) view.findViewById(R.id.badge))
//					.setImageResource(R.drawable.badge_sa);
//		} else if (radioOption.getCheckedRadioButtonId() == R.id.custom_info_window) {
//			ImageView imageView = (ImageView) view.findViewById(R.id.badge);
//			imageView.setImageResource(R.drawable.badge_wa);
//		}
		String title = marker.getTitle();
		TextView titleUi = ((TextView) view.findViewById(R.id.title));
		if (title != null) {
			SpannableString titleText = new SpannableString(title);
			titleText.setSpan(new ForegroundColorSpan(Color.RED), 0,
					titleText.length(), 0);
			titleUi.setTextSize(15);
			titleUi.setText(titleText);

		} else {
			titleUi.setText("");
		}
		String snippet = marker.getSnippet();
		TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
		if (snippet != null) {
			SpannableString snippetText = new SpannableString(snippet);
			snippetText.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
					snippetText.length(), 0);
			snippetUi.setTextSize(20);
			snippetUi.setText(snippetText);
		} else {
			snippetUi.setText("");
		}
	}

	private void setLocation(Address address) {
		
		// TODO Auto-generated method stub
		aMap.animateCamera(CameraUpdateFactory.changeLatLng(new LatLng(address.latitude, address.longitude)));
		
		
//		aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
//				.position(new LatLng(address.latitude, address.longitude)).title("")
//				.snippet(address.name)
//				.perspective(true).draggable(false).period(50));
	}
	


	
	/**
	 * 对marker标注点点击响应事件
	 */
	@Override
	public boolean onMarkerClick(final Marker marker) {
//		if (marker.equals(marker2)) {
//			if (aMap != null) {
//				jumpPoint(marker);
//			}
//		}
		//markerText.setText("你点击的是" + marker.getTitle());
		return false;
	}




	/**
	 * 绘制系统默认的1种marker背景图片
	 */
	public void drawMarkers(List<Address > list ) {
		for(int i=0;i<list.size();i++){
			Address address = list.get(i);
			Marker marker = aMap.addMarker(new MarkerOptions()
				.position(new LatLng(address.latitude, address.longitude))
				.title("")
				.snippet(address.name)
				.icon(BitmapDescriptorFactory
						.defaultMarker(BitmapDescriptorFactory.HUE_RED))
				.draggable(true));
			//marker.setRotateAngle(90);// 设置marker旋转90度
			//marker.showInfoWindow();// 设置默认显示一个infowinfow
		}

	}



	
    /** 
     * 方法必须重写 
     */  
    @Override  
    protected void onResume() {  
        super.onResume();  
        mapView.onResume();  
    }  
  
    /** 
     * 方法必须重写 
     */  
    @Override  
    protected void onPause() {  
        super.onPause();  
        mapView.onPause();  
        deactivate();
    }  
      
    /** 
     * 方法必须重写 
     */  
    @Override  
    protected void onSaveInstanceState(Bundle outState) {  
        super.onSaveInstanceState(outState);  
        mapView.onSaveInstanceState(outState);  
    }  
  
    /** 
     * 方法必须重写 
     */  
    @Override  
    protected void onDestroy() {  
        super.onDestroy();  
        mapView.onDestroy();  
    }


	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		
		if (mListener != null && aLocation != null) {
			mListener.onLocationChanged(aLocation);// 显示系统小蓝点
			float bearing = aMap.getCameraPosition().bearing;
			aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
		}
		// TODO Auto-generated method stub
		
	}  
    
    


}
